package cn.com.manager.credentials;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {
	private Cache<String, AtomicInteger> cache;

	public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
		cache = cacheManager.getCache("passwordRetryCache");
	}

	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		String username = (String) token.getPrincipal();
		AtomicInteger retryCount = cache.get(username);
		if (retryCount != null) {
			if (retryCount.get() > 3) {
				throw new ExcessiveAttemptsException();// 尝试错误密码次数过多
			}
		} else {
			retryCount = new AtomicInteger(0);
		}
		boolean check = super.doCredentialsMatch(token, info);
		if (!check) {
			retryCount.incrementAndGet();
			cache.put(username, retryCount);
		}else{
			cache.remove(username);
		}
		return check;
	}
}
